<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>分类管理</title>
    <!-- 引入Vue.js -->
    <script src="../../js/vue.js"></script>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="../../css/index.css">
    <!-- 引入Element UI组件库 -->
    <script src="../../js/index.js"></script>
    <!-- 引入axios -->
    <script src="../../js/axios.min.js"></script>
    <style>
        .el-table .el-table__fixed-right {
            height: 100% !important;
        }
        .search-form .el-form-item {
            margin-bottom: 10px;
        }
        .tree-container {
            margin-top: 20px;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            padding: 10px;
            max-height: 400px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
<div id="app" class="app1">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="分类编码">
            <el-input size="mini" v-model="searchForm.categoryCode" placeholder="请输入分类编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="分类名称">
            <el-input size="mini" v-model="searchForm.categoryName" placeholder="请输入分类名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
            <el-cascader
                    size="mini"
                    v-model="searchForm.parentId"
                    :options="categoryTree"
                    :props="{ checkStrictly: true, value: 'categoryId', label: 'categoryName', children: 'children' }"
                    clearable
                    placeholder="请选择父级分类"
                    style="width: 200px">
            </el-cascader>
        </el-form-item>
        <el-form-item label="分类级别">
            <el-select v-model="searchForm.level" placeholder="请选择级别" size="mini" clearable>
                <el-option label="一级分类" :value="1"></el-option>
                <el-option label="二级分类" :value="2"></el-option>
                <el-option label="三级分类" :value="3"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" size="mini" clearable>
                <el-option label="正常" value="0"></el-option>
                <el-option label="停用" value="1"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button size="mini" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            <el-button size="mini" @click="resetSearch">重置</el-button>
            <el-button size="mini" type="primary" @click="handleAdd">添加分类</el-button>
            <el-button size="mini" type="success" @click="loadCategoryTree">刷新树形结构</el-button>
        </el-form-item>
    </el-form>

    <!-- 分类树形结构 -->
    <div class="tree-container">
        <el-tree
                :data="categoryTree"
                node-key="categoryId"
                default-expand-all
                :expand-on-click-node="false"
                :props="defaultProps">
            <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                    <el-button
                            type="text"
                            size="mini"
                            @click="() => handleAddChild(data)">
                        添加子分类
                    </el-button>
                    <el-button
                            type="text"
                            size="mini"
                            @click="() => handleEdit(node, data)">
                        编辑
                    </el-button>
                    <el-button
                            type="text"
                            size="mini"
                            style="color: #F56C6C"
                            @click="() => handleDelete(node, data)">
                        删除
                    </el-button>
                </span>
            </span>
        </el-tree>
    </div>

    <!-- 分类列表 -->
    <el-table :data="tableData" style="width: 100%" border height="500">
        <el-table-column prop="categoryId" label="分类ID" width="100"></el-table-column>
        <el-table-column prop="parentId" label="父级ID" width="100">
            <template slot-scope="scope">
                {{ scope.row.parentId || '无' }}
            </template>
        </el-table-column>
        <el-table-column prop="categoryCode" label="分类编码" width="120"></el-table-column>
        <el-table-column prop="categoryName" label="分类名称" width="150"></el-table-column>
        <el-table-column prop="level" label="分类级别" width="100">
            <template slot-scope="scope">
                <el-tag :type="scope.row.level === 1 ? 'primary' : scope.row.level === 2 ? 'success' : 'warning'">
                    {{ scope.row.level }}级分类
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="orderNum" label="显示顺序" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="80">
            <template slot-scope="scope">
                <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                    {{ scope.row.status === '0' ? '正常' : '停用' }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="delFlag" label="删除标志" width="100">
            <template slot-scope="scope">
                <el-tag :type="scope.row.delFlag === '0' ? 'success' : 'danger'">
                    {{ scope.row.delFlag === '0' ? '存在' : '删除' }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建者" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
            <template slot-scope="scope">
                {{ scope.row.createTime ? formatDateTime(scope.row.createTime) : '' }}
            </template>
        </el-table-column>
        <el-table-column prop="updateBy" label="更新者" width="100"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="160">
            <template slot-scope="scope">
                {{ scope.row.updateTime ? formatDateTime(scope.row.updateTime) : '' }}
            </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="120"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
            <template slot-scope="scope">
                <el-button size="mini" @click="handleAddChild(scope.row)">添加子类</el-button>
                <el-button size="mini" @click="handleEdit(null, scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(null, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
            <el-form-item label="父级分类" prop="parentId">
                <el-cascader
                        v-model="form.parentId"
                        :options="categoryTree"
                        :props="{ checkStrictly: true, value: 'categoryId', label: 'categoryName', children: 'children' }"
                        clearable
                        placeholder="请选择父级分类"
                        style="width: 100%">
                </el-cascader>
            </el-form-item>

            <el-form-item label="分类编码" prop="categoryCode">
                <el-input v-model="form.categoryCode" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="分类名称" prop="categoryName">
                <el-input v-model="form.categoryName" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="分类级别" prop="level">
                <el-select v-model="form.level" placeholder="请选择分类级别" style="width: 100%">
                    <el-option label="一级分类" :value="1"></el-option>
                    <el-option label="二级分类" :value="2"></el-option>
                    <el-option label="三级分类" :value="3"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="显示顺序" prop="orderNum">
                <el-input-number v-model="form.orderNum" :min="0" :max="999" controls-position="right" style="width: 100%"></el-input-number>
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                    <el-radio label="0">正常</el-radio>
                    <el-radio label="1">停用</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" :rows="3"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button @click="resetForm('form')">重置</el-button>
            <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                tableData: [], // 表格数据
                categoryTree: [], // 树形结构数据
                currentPage: 1, // 当前页码
                pageSize: 10, // 每页显示的条数
                total: 0, // 分页数据的总数
                searchForm: {
                    categoryCode: '',
                    categoryName: '',
                    parentId: null,
                    level: null,
                    status: ''
                }, // 搜索条件
                title: '添加分类', // 对话框标题
                dialogFormVisible: false, // 对话框是否可见
                defaultProps: {
                    children: 'children',
                    label: 'categoryName'
                },
                form: {
                    categoryId: '',
                    parentId: null,
                    categoryCode: '',
                    categoryName: '',
                    level: 1,
                    orderNum: 0,
                    status: '0',
                    delFlag: '0',
                    createBy: '',
                    createTime: '',
                    updateBy: '',
                    updateTime: '',
                    remark: ''
                },
                rules: {
                    categoryCode: [
                        { required: true, message: '请输入分类编码', trigger: 'blur' }
                    ],
                    categoryName: [
                        { required: true, message: '请输入分类名称', trigger: 'blur' }
                    ],
                    level: [
                        { required: true, message: '请选择分类级别', trigger: 'change' }
                    ],
                    orderNum: [
                        { required: true, message: '请输入显示顺序', trigger: 'blur' }
                    ],
                    status: [
                        { required: true, message: '请选择状态', trigger: 'change' }
                    ]
                }
            }
        },
        created() {
            this.loadData();
            this.loadCategoryTree();
        },
        methods: {
            // 加载分类数据
            loadData() {
                let _this = this;
                // 处理父级ID（如果是数组，取最后一个值）
                let searchData = Object.assign({}, this.searchForm);
                if (Array.isArray(searchData.parentId) && searchData.parentId.length > 0) {
                    searchData.parentId = searchData.parentId[searchData.parentId.length - 1];
                }

                axios.post('/vegetablemarketexpress/category/queryByPage', {
                    "pageNo": this.currentPage,
                    "pageSize": this.pageSize,
                    "data": searchData
                }).then(function(response) {
                    if (response.data.code==200) {
                        _this.tableData = response.data.data.list;
                        _this.total = response.data.data.total;
                    }
                }).catch(function(error) {
                    console.log(error);
                    _this.$message.error('数据加载失败');
                });
            },

            // 加载分类树形结构
            loadCategoryTree() {
                let _this = this;
                axios.get('/vegetablemarketexpress/category/queryCategoryTree')
                    .then(function(response) {
                        if (response.data.code==200) {
                            // 从 Result 对象的 data 字段中获取分类列表
                            const categories = response.data.data;
                            _this.categoryTree = _this.buildTree(categories);
                        }else {
                            _this.$message.error('树形数据加载失败：' + response.data.msg);
                        }
                    })
                    .catch(function(error) {
                        console.error('树形结构请求失败：', error);
                        _this.$message.error('树形数据加载失败');
                    });
            },

            // 构建树形结构
            buildTree(categories) {
                const map = {};
                const tree = [];
            // 校验输入是否为数组
                if (!Array.isArray(categories)) {
                    console.error('分类数据不是数组');
                    return [];
                }
                // 创建节点映射表（用 categoryId 作为键）
                categories.forEach(category => {
                    // 确保每个分类有唯一标识 categoryId
                    if (category.categoryId === undefined) {
                        console.warn('分类缺少 categoryId：', category);
                        return;
                    }
                    map[category.categoryId] = { ...category, children: [] };
                    //category.children = [];
                });

                // 构建树形结构 构建父子关系
                categories.forEach(category => {
                    const currentNode = map[category.categoryId];
                    if (!currentNode) return;

                    if (category.parentId && map[category.parentId]) {
                        // 有父级，添加到父节点的 children 中
                        map[category.parentId].children.push(currentNode);
                    } else {
                        // 无父级（parentId 为 null 或 父级不存在），作为根节点
                        tree.push(currentNode);
                    }
                });

                return tree;
            },

            // 格式化日期时间
            formatDateTime(dateTime) {
                if (!dateTime) return '';
                if (typeof dateTime === 'string') {
                    return dateTime.replace('T', ' ').substring(0, 19);
                }
                return dateTime;
            },

            // 每页显示条数改变
            handleSizeChange(val) {
                this.pageSize = val;
                this.currentPage = 1;
                this.loadData();
            },

            // 当前页码改变
            handleCurrentChange(val) {
                this.currentPage = val;
                this.loadData();
            },

            // 搜索
            search() {
                this.currentPage = 1;
                this.loadData();
            },

            // 重置搜索条件
            resetSearch() {
                this.searchForm = {
                    categoryCode: '',
                    categoryName: '',
                    parentId: null,
                    level: null,
                    status: ''
                };
                this.currentPage = 1;
                this.loadData();
            },

            // 提交表单
            submitForm(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        let url = '/vegetablemarketexpress/category/add';
                        let successMsg = '添加成功';

                        if (this.title === '修改分类') {
                            url = '/vegetablemarketexpress/category/update';
                            successMsg = '修改成功';
                        }

                        // 处理父级ID（如果是数组，取最后一个值）
                        let submitData = Object.assign({}, this.form);
                        if (Array.isArray(submitData.parentId) && submitData.parentId.length > 0) {
                            submitData.parentId = submitData.parentId[submitData.parentId.length - 1];
                        } else {
                            submitData.parentId = null;
                        }

                        let _this = this;
                        axios.post(url, submitData)
                            .then(function(response) {
                                if (response.data.code ==200) {
                                    _this.$message({
                                        message: successMsg,
                                        type: 'success'
                                    });
                                    _this.loadData();
                                    _this.loadCategoryTree();
                                    _this.dialogFormVisible = false;
                                } else {
                                    _this.$message.error('操作失败');
                                }
                            })
                            .catch(function(error) {
                                console.log(error);
                                _this.$message.error('操作异常');
                            });
                    } else {
                        this.$message.error('表单验证失败');
                        return false;
                    }
                });
            },

            // 重置表单
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },

            // 处理添加
            handleAdd() {
                this.dialogFormVisible = true;
                this.title = "添加分类";
                this.form = {
                    categoryId: '',
                    parentId: null,
                    categoryCode: '',
                    categoryName: '',
                    level: 1,
                    orderNum: 0,
                    status: '0',
                    delFlag: '0',
                    createBy: '',
                    createTime: '',
                    updateBy: '',
                    updateTime: '',
                    remark: ''
                };
            },

            // 处理添加子分类
            handleAddChild(row) {
                this.dialogFormVisible = true;
                this.title = "添加子分类";
                this.form = {
                    categoryId: '',
                    parentId: row ? [row.categoryId] : null,
                    categoryCode: '',
                    categoryName: '',
                    level: row ? row.level + 1 : 1,
                    orderNum: 0,
                    status: '0',
                    delFlag: '0',
                    createBy: '',
                    createTime: '',
                    updateBy: '',
                    updateTime: '',
                    remark: ''
                };

                // 限制分类级别不能超过3级
                if (this.form.level > 3) {
                    this.$message.warning('分类级别不能超过3级');
                    this.form.level = 3;
                }
            },

            // 处理编辑
            handleEdit(node, row) {
                this.dialogFormVisible = true;
                this.title = "修改分类";
                this.form = Object.assign({}, row);

                // 设置父级ID为数组格式（用于级联选择器）
                if (this.form.parentId) {
                    this.form.parentId = [this.form.parentId];
                }
            },

            // 处理删除
            handleDelete(node, row) {
                this.$confirm('此操作将删除该分类, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let _this = this;
                    axios.delete('/vegetablemarketexpress/category/deleteByCategoryId?categoryId=' + row.categoryId)
                        .then(function(response) {
                            if (response.data.code==200) {
                                _this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                _this.loadData();
                                _this.loadCategoryTree();
                            } else {
                                _this.$message.error('删除失败');
                            }
                        })
                        .catch(function(error) {
                            console.log(error);
                            _this.$message.error('删除异常');
                        });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        }
    });
</script>
</body>
</html>